package ThreadPool;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * 手动实现一个定时器任务
 */
class MyTimerTask /*implements Comparable<MyTimerTask>*/ {
    private Runnable runnable;
    private long time;

    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    // 获取任务在何时被执行
    public long getTime() {
        return time;
    }

    // 执行任务
    public void run() {
        runnable.run();
    }

    // 比较任务执行时间
//    @Override
//    public int compareTo(MyTimerTask o) {
//        return (int) (this.time - o.time);
//    }

}

/**
 * 手动实现定时器类
 */
class MyTimer {
    // 使用队列存储任务
//    PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    PriorityQueue<MyTimerTask> queue = new PriorityQueue<>((a, b) -> (int)(a.getTime() - b.getTime()));

    Object lock = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized(lock) {
            MyTimerTask task = new MyTimerTask(runnable,delay);
            queue.add(task);
            lock.notify();
        }
   }


    public MyTimer() {
        // 创建新线程, 线程执行内部逻辑
        Thread t = new Thread(() -> {
            try {
                while (true) {
                    synchronized(lock) {
                        // 1. 获取队列首元素
                        MyTimerTask task = queue.peek();

                        while (task == null) {
                            lock.wait();
                            task = queue.peek();
                        }

                        long curTime = System.currentTimeMillis();
                        // 2. 判断时间是否要执行任务
                        if (task.getTime() >= curTime) {
                            // 时间到了, 执行任务
                            task.run();
                            // 任务执行完毕, 移除当前任务
                            queue.poll();
                        } else {
                            // 时间没到
                            lock.wait(task.getTime() - curTime);
                        }
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException("wait 终止");
            }

        });
        t.start();
    }


}
public class demo4 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer timer = new MyTimer();
        timer.schedule(() -> {
            System.out.println("hello 1000ms");
        },1000);

        timer.schedule(() -> {
            System.out.println("hello 2000ms");
        },2000);

        timer.schedule(() -> {
            System.out.println("hello 3000ms");
        },3000);

    }
}
